package com.boil.qz.safekavass.service;

import com.boil.qz.safekavass.model.WeixinSendredpackRecordEntity;
import com.boil.qz.safekavass.pojo.WeixinGethbinfoParamVo;
import com.boil.qz.safekavass.repository.WeixinSendredpackRecordRepository;
import com.boil.qz.safekavass.weixin.util.WeixinUtils;
import com.boil.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ChenYong on 2017-11-01.
 * <br>
 * 微信发普通红包记录 Service。
 */
@Service
public class WeixinSendredpackRecordService extends JpaRepositoryService<WeixinSendredpackRecordEntity, Long> {
    /**
     * 注入微信发普通红包实体仓库
     */
    @Autowired
    private WeixinSendredpackRecordRepository weixinSendredpackRecordRepository;

    /**
     * 根据返回状态码、业务结果和红包状态查询红包记录实例 <code>List</code>。
     *
     * @param returnCode 返回状态码
     * @param resultCode 业务结果
     * @param status     红包状态
     * @return 红包记录实例 <code>List</code>
     */
    List<WeixinSendredpackRecordEntity> findAllByReturnCodeAndResultCodeAndStatusInAndReasonIsNull(String returnCode, String resultCode, List<String> status) {
        return weixinSendredpackRecordRepository.findAllByReturnCodeAndResultCodeAndStatusInAndReasonIsNull(returnCode, resultCode, status);
    }

    /**
     * 同步微信服务器上的红包记录到本地数据库中。
     */
    public void doSyncWeixinRedpackRecord() {
        // 红包状态
        List<String> statuss = new ArrayList<String>();
        statuss.add(WeixinUtils.STATUS_SENDING);
        statuss.add(WeixinUtils.STATUS_SENT);
        statuss.add(WeixinUtils.STATUS_RFUND_ING);

        List<WeixinSendredpackRecordEntity> weixinSendredpackRecordEntities = findAllByReturnCodeAndResultCodeAndStatusInAndReasonIsNull(WeixinUtils.SUCCESS_STR, WeixinUtils.SUCCESS_STR, statuss);

        for (WeixinSendredpackRecordEntity weixinSendredpackRecordEntity : weixinSendredpackRecordEntities) {
            try {
                // 红包记录参数实例
                WeixinGethbinfoParamVo weixinGethbinfoParamVo = new WeixinGethbinfoParamVo();
                weixinGethbinfoParamVo.setNonce_str(Utils.getUuid().toUpperCase());
                weixinGethbinfoParamVo.setMch_billno(weixinSendredpackRecordEntity.getMchBillno());
                weixinGethbinfoParamVo.setMch_id(weixinSendredpackRecordEntity.getMchId());
                weixinGethbinfoParamVo.setAppid(WeixinUtils.APP_ID);
                weixinGethbinfoParamVo.setBill_type(WeixinUtils.BILL_TYPE_MCHT);
                weixinGethbinfoParamVo.setSign(WeixinUtils.getWeixinGethbinfoSign(weixinGethbinfoParamVo));

                // 调用接口查询红包记录
                String gethbinfoResultXml = WeixinUtils.sendCertHttpsPost(WeixinUtils.URL_POST_GETHBINFO, Utils.bean2Xml(weixinGethbinfoParamVo));
                // 查询红包记录结果
                Map<String, String> gethbinfoResultMap = Utils.xml2Map(gethbinfoResultXml);
                // 返回状态码
                String return_code = gethbinfoResultMap.get(WeixinUtils.RETURN_CODE_STR);
                // 返回信息
                String return_msg = gethbinfoResultMap.get(WeixinUtils.RETURN_MSG_STR);

                // 通信成功
                if (WeixinUtils.SUCCESS_STR.equals(return_code)) {
                    String result_code = gethbinfoResultMap.get(WeixinUtils.RESULT_CODE_STR);

                    // 查询红包记录成功
                    if (WeixinUtils.SUCCESS_STR.equals(result_code)) {
                        weixinSendredpackRecordEntity.setReturnCode(return_code);
                        weixinSendredpackRecordEntity.setReturnMsg(return_msg);
                        weixinSendredpackRecordEntity.setResultCode(result_code);
                        weixinSendredpackRecordEntity.setErrCode(gethbinfoResultMap.get(WeixinUtils.ERR_CODE_STR));
                        weixinSendredpackRecordEntity.setErrCodeDes(gethbinfoResultMap.get(WeixinUtils.ERR_CODE_DES_STR));
                        weixinSendredpackRecordEntity.setSign(gethbinfoResultMap.get(WeixinUtils.SIGN_STR));
                        weixinSendredpackRecordEntity.setMchBillno(gethbinfoResultMap.get(WeixinUtils.MCH_BILLNO_STR));
                        weixinSendredpackRecordEntity.setMchId(gethbinfoResultMap.get(WeixinUtils.MCH_ID_STR));
                        weixinSendredpackRecordEntity.setDetailId(gethbinfoResultMap.get(WeixinUtils.DETAIL_ID_STR));
                        weixinSendredpackRecordEntity.setStatus(gethbinfoResultMap.get(WeixinUtils.STATUS_STR));
                        weixinSendredpackRecordEntity.setSendType(gethbinfoResultMap.get(WeixinUtils.SEND_TYPE_STR));
                        weixinSendredpackRecordEntity.setHbType(gethbinfoResultMap.get(WeixinUtils.HB_TYPE_STR));
                        weixinSendredpackRecordEntity.setReason(gethbinfoResultMap.get(WeixinUtils.REASON_STR));
                        weixinSendredpackRecordEntity.setSendTime(gethbinfoResultMap.get(WeixinUtils.SEND_TIME_STR));
                        weixinSendredpackRecordEntity.setRefundTime(gethbinfoResultMap.get(WeixinUtils.REFUND_TIME_STR));
                        weixinSendredpackRecordEntity.setWishing(gethbinfoResultMap.get(WeixinUtils.WISHING_STR));
                        weixinSendredpackRecordEntity.setRemark(gethbinfoResultMap.get(WeixinUtils.REMARK_STR));
                        weixinSendredpackRecordEntity.setActName(gethbinfoResultMap.get(WeixinUtils.ACT_NAME_STR));
                        weixinSendredpackRecordEntity.setOpenid(gethbinfoResultMap.get(WeixinUtils.OPENID_STR));
                        weixinSendredpackRecordEntity.setRcvTime(gethbinfoResultMap.get(WeixinUtils.RCV_TIME_STR));

                        if (StringUtils.isNotBlank(gethbinfoResultMap.get(WeixinUtils.TOTAL_NUM_STR))) {
                            weixinSendredpackRecordEntity.setTotalNum(Integer.parseInt(gethbinfoResultMap.get(WeixinUtils.TOTAL_NUM_STR)));
                        }

                        if (StringUtils.isNotBlank(gethbinfoResultMap.get(WeixinUtils.TOTAL_AMOUNT_STR))) {
                            weixinSendredpackRecordEntity.setTotalAmount(Integer.parseInt(gethbinfoResultMap.get(WeixinUtils.TOTAL_AMOUNT_STR)));
                        }

                        if (StringUtils.isNotBlank(gethbinfoResultMap.get(WeixinUtils.REFUND_AMOUNT_STR))) {
                            weixinSendredpackRecordEntity.setRefundAmount(Integer.parseInt(gethbinfoResultMap.get(WeixinUtils.REFUND_AMOUNT_STR)));
                        }

                        if (StringUtils.isNotBlank(gethbinfoResultMap.get(WeixinUtils.AMOUNT_STR))) {
                            weixinSendredpackRecordEntity.setAmount(Integer.parseInt(gethbinfoResultMap.get(WeixinUtils.AMOUNT_STR)));
                        }

                        flush();

                        log.debug("微信红包记录作业（WeixinRedpackRecordTask）--->商户订单号：{}，同步微信服务器上的红包记录到本地成功", weixinSendredpackRecordEntity.getMchBillno());
                    }
                }
            } catch (Exception e) {
                log.error("微信红包记录作业（WeixinRedpackRecordTask）--->商户订单号：{}，同步微信服务器上的红包记录到本地出现异常：{}", weixinSendredpackRecordEntity.getMchBillno(), e);
            }
        }
    }
}